package com.dayaokeji.rhythmschoolstudent.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.api.SystemApi;
import com.orhanobut.logger.Logger;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import okhttp3.Headers;
import okhttp3.ResponseBody;

/**
 * Created by Gorden on 2017/10/9.
 * 时间处理工具类
 */

public class TimeUtils {

    private static final SystemApi systemApi = ApiUtils.getApi(SystemApi.class);

    /**
     * 获取网络时间
     * @return
     */
    @SuppressLint("StaticFieldLeak")
    public static void webDateTime(final RequestWebDateTimeListener requestWebDateTimeListener) {
//        new AsyncTimeTask(requestWebDateTimeListener).execute(WEB_DATE_TIME_URL);
        asyncWebTime(requestWebDateTimeListener);
    }

    public static void asyncNetDate() {
        TimeUtils.webDateTimeForTimestamp(new TimeUtils.RequestWebDateTimeTimestampListener() {
            @Override
            public void requestDateTime(Long webDateTime) {
                Logger.d("async web date = "+DateUtils.format(webDateTime, DateUtils.FORMAT_DATE));
                PrefUtils.setWebDate(DateUtils.format(webDateTime, DateUtils.FORMAT_DATE));
            }
        });
    }

    private static void asyncWebTime(final RequestWebDateTimeListener requestWebDateTimeListener) {
        systemApi.webDate().enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                if (response.isSuccessful() && response.raw() != null) {
                    final Headers headers = response.raw().headers();
                    if (headers != null && headers.size() > 0) {
                        final Date date = headers.getDate("Date");
                        if (date != null) {
                            Logger.d("web date ========= "+DateUtils.format(date,DateUtils.FORMAT_DATETIME));
                            if (requestWebDateTimeListener != null) {
                                requestWebDateTimeListener.requestDateTime(DateUtils.format(date,DateUtils.FORMAT_DATETIME));
                            }
                        }

                    }
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                Logger.d(t != null ? t.getMessage() : "网络时间校准失败");
                asyncWebTime(requestWebDateTimeListener);
            }
        });
    }
    /**
     * 比对签到时间
     * @param currentDateStr
     * @param beginDateStr
     * @return 1 : 可以进行签到 2 : 还未进行签到 3 ：签到已结束
     */
    public static int compareDate(String currentDateStr,String beginDateStr) {
        return compareDate(currentDateStr,beginDateStr,null,null);
    }

    /**
     * 比对签到时间
     * @param currentDateStr
     * @param beginDateStr
     * @return 1 : 可以进行签到 2 : 还未进行签到 3 ：签到已结束
     */
    public static int compareDate(String currentDateStr,String beginDateStr,String signStartTime,String signEndTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        Date signBeginAfterTime;
        Date signBeginBeforeTime;
        try {
            Date currentDate = sdf.parse(currentDateStr);

            beginDateStr = beginDateStr.replace("\n\t\t", " ");
            Date beginDate = sdf.parse(beginDateStr);
            if (compareYearMonthDay(currentDate,beginDate) == 1) {
                if (TextUtils.isEmpty(signStartTime) && TextUtils.isEmpty(signEndTime)) {
                    Calendar signAfterDateCalendar = Calendar.getInstance();
                    Calendar signBeforeDateCalendar = Calendar.getInstance();
                    // 会议开始后 30分钟内签到有效
                    signAfterDateCalendar.setTime(beginDate);
                    signAfterDateCalendar.add(Calendar.MINUTE,30);
                    // 会议开始前 10分钟可签到
                    signBeforeDateCalendar.setTime(beginDate);
                    signBeforeDateCalendar.add(Calendar.MINUTE,-10);
                    signBeginAfterTime = sdf.parse(sdf.format(signAfterDateCalendar.getTime()));
                    signBeginBeforeTime = sdf.parse(sdf.format(signBeforeDateCalendar.getTime()));
                }else{
                    signBeginAfterTime = sdf.parse(signEndTime);
                    signBeginBeforeTime = sdf.parse(signStartTime);
                }
                if (currentDate.after(signBeginBeforeTime) && currentDate.before(signBeginAfterTime)) {
                    return 1;
                }else if (currentDate.equals(signBeginBeforeTime) || currentDate.equals(signBeginAfterTime)) {
                    return 1;
                }else if (currentDate.before(signBeginBeforeTime)) {
                    return 2;
                }else{
                    return 3;
                }
            }else if (compareYearMonthDay(currentDate,beginDate) == 3){
                return  3;
            }else if (compareYearMonthDay(currentDate,beginDate) == 2){
                return 2;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return 3;
    }

    public static String getCompareDateTime(String currentDateStr,String beginDateStr,String signStartTime,String signEndTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        Date signBeginAfterTime;
        Date signBeginBeforeTime;
        try {
            Date currentDate = sdf.parse(currentDateStr);

            beginDateStr = beginDateStr.replace("\n\t\t", " ");
            Date beginDate = sdf.parse(beginDateStr);
            if (compareYearMonthDay(currentDate,beginDate) == 1) {
                if (TextUtils.isEmpty(signStartTime) && TextUtils.isEmpty(signEndTime)) {
                    Calendar signAfterDateCalendar = Calendar.getInstance();
                    Calendar signBeforeDateCalendar = Calendar.getInstance();
                    // 会议开始后 30分钟内签到有效
                    signAfterDateCalendar.setTime(beginDate);
                    signAfterDateCalendar.add(Calendar.MINUTE,30);
                    // 会议开始前 10分钟可签到
                    signBeforeDateCalendar.setTime(beginDate);
                    signBeforeDateCalendar.add(Calendar.MINUTE,-10);
                    signBeginAfterTime = sdf.parse(sdf.format(signAfterDateCalendar.getTime()));
                    signBeginBeforeTime = sdf.parse(sdf.format(signBeforeDateCalendar.getTime()));
                }else{
                    signBeginAfterTime = sdf.parse(signEndTime);
                    signBeginBeforeTime = sdf.parse(signStartTime);
                }
                if (currentDate.before(signBeginBeforeTime)) {
                    CharSequence s = android.text.format.DateUtils.getRelativeTimeSpanString(signBeginBeforeTime.getTime(), currentDate.getTime(), android.text.format.DateUtils.MINUTE_IN_MILLIS);
                    return s.toString();
                }
            }else if (compareYearMonthDay(currentDate,beginDate) == 2){
                CharSequence s = android.text.format.DateUtils.getRelativeTimeSpanString(beginDate.getTime(), currentDate.getTime(), android.text.format.DateUtils.MINUTE_IN_MILLIS);
                return s.toString();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    private static int compareYearMonthDay(Date currentDate, Date beginDate) {
        if (currentDate.getYear() == beginDate.getYear() && currentDate.getMonth() == beginDate.getMonth() && currentDate.getDay() == beginDate.getDay()) {
            return  1;
        }else if (currentDate.getYear() > beginDate.getYear() || currentDate.getMonth() > beginDate.getMonth() || currentDate.getDay() > beginDate.getDay()) {
            return 3;
        }else{
            return 2;
        }
    }


    public interface RequestWebDateTimeListener{
        void requestDateTime(String webDateTime);
    }

    public interface RequestWebDateTimeTimestampListener{
        void requestDateTime(Long webDateTime);
    }


    /**
     * 获取网络时间戳
     * @return
     */
    @SuppressLint("StaticFieldLeak")
    public static void webDateTimeForTimestamp(final RequestWebDateTimeTimestampListener requestWebDateTimeTimestampListener) {
        systemApi.webDate().enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                if (response != null && response.raw() != null) {
                    final Headers headers = response.raw().headers();
                    if (headers != null && headers.size() > 0) {
                        final Date date = headers.getDate("Date");
                        if (date != null) {
                            Logger.d(DateUtils.format(date,DateUtils.FORMAT_DATETIME));
                            if (requestWebDateTimeTimestampListener != null) {
                                requestWebDateTimeTimestampListener.requestDateTime(date.getTime());
                            }
                        }

                    }
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                Logger.d(t != null ? t.getMessage() : "网络时间校准失败");
                webDateTimeForTimestamp(requestWebDateTimeTimestampListener);
            }
        });
    }
}
